package org.darkforest.ucenter.service.impl;

import net.sf.json.JSONObject;
import org.darkforest.common.util.DateUtil;
import org.darkforest.dao.mapper.*;
import org.darkforest.enums.OrderStatusEnum;
import org.darkforest.enums.PdLogTypeEnum;
import org.darkforest.enums.SellerStateEnum;
import org.darkforest.model.*;
import org.darkforest.ucenter.service.ReturnService;
import org.darkforest.ucenter.service.UserOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 项目名称         :bwmall-ucenter
 * 文件名           :OrderServiceImpl.java
 * 开发公司及作者    :陈超
 * 版本号及开发日期  :Rev. 1.00 (2015年2月1日)
 */
@Service
public class UserOrderServiceImpl implements UserOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private EvaluateGoodsMapper evaluateGoodsMapper;
    @Autowired
    private RefundReturnMapper refundReturnMapper;
    @Autowired
    private OrderCommonMapper orderCommonMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private PdLogMapper pdLogMapper;
    @Autowired
    private ReturnService returnService;
    @Autowired
    private ExpressMapper expressMapper;

    @Override
    public OrderSearchBean getOrderListByUser(OrderSearchBean page) {
        page.setResultList(orderMapper.selectByBuyerIdLimit(page));
        return page;
    }

    @Override
    public List<OrderVo> getDeletedOrderListByUser(OrderSearchBean page) {
        page.setDeleteState(1);
        page.setResultList(orderMapper.selectByBuyerIdLimit(page));
        return page.getResultList();
    }

    @Override
    public OrderVo getOrderDetailById(Integer id, Integer buyerId) {
        Map<String, Integer> param = new HashMap<String, Integer>();
        param.put("id", id);
        param.put("buyerId", buyerId);

        OrderVo vo = orderMapper.selectById(param);

        // 个人买时
        if (vo.getCommon().getPostType() == 1) {
            // 待付款时都显示到一个订单，付款后，各个订单显示各个订单的商品
            if ("10".equals(vo.getOrderState())) {
                Order param1 = new Order();
                param1.setOrderBatchNumber(vo.getOrderBatchNumber());
                List<Order> orders = orderMapper.findOrderWithGoodsByCondition(param1);
                if (orders.size() > 1) {
                    List<OrderGoods> orderGoodsList = new ArrayList<OrderGoods>();
                    BigDecimal orderAmount = new BigDecimal(0);
                    BigDecimal goodsAmount = new BigDecimal(0);
                    for (Order order1 : orders) {
                        orderGoodsList.addAll(order1.getOrderGoodsList());
                        orderAmount = orderAmount.add(order1.getOrderAmount());
                        goodsAmount = goodsAmount.add(order1.getGoodsAmount());
                    }
                    vo.setOrderGoodsList(orderGoodsList);
                    vo.setOrderAmount(orderAmount);
                    vo.setGoodsAmount(goodsAmount);
                }
            }
        }

        //  送礼时
        if (vo.getCommon().getPostType() == 2) {
            Order param1 = new Order();
            param1.setOrderBatchNumber(vo.getOrderBatchNumber());
            List<Order> orders = orderMapper.findOrderWithGoodsByCondition(param1);
            if (orders.size() > 1) {
                List<OrderGoods> orderGoodsList = new ArrayList<OrderGoods>();
                BigDecimal orderAmount = new BigDecimal(0);
                BigDecimal goodsAmount = new BigDecimal(0);
                for (Order order1 : orders) {
                    orderGoodsList.addAll(order1.getOrderGoodsList());
                    orderAmount = orderAmount.add(order1.getOrderAmount());
                    goodsAmount = goodsAmount.add(order1.getGoodsAmount());
                }
                vo.setOrderGoodsList(orderGoodsList);
                vo.setOrderAmount(orderAmount);
                vo.setGoodsAmount(goodsAmount);
            }
        }
        if (vo.getCommon() != null && vo.getCommon().getAddress() == null) {
            try {
                vo.getCommon().setAddress((Address) JSONObject.toBean(JSONObject.fromObject(vo.getCommon().getReciverInfo()), Address.class));
            } catch (Exception e) {

            }
            try {
                JSONObject obj = JSONObject.fromObject(vo.getCommon().getInvoiceInfo());
                vo.getCommon().setInvoiceInfo(obj.get("invTitle") + " " + obj.get("invContent"));
            } catch (Exception e) {

            }
        }

        // 快递公司的取得
        if (vo.getCommon() != null && vo.getCommon().getShippingExpressId() != null) {
            int expressId =  vo.getCommon().getShippingExpressId();
            // orderCommonMapper.insertSelective 时， Integer的数据null -->> 0
            if (expressId > 0) {
                Express express = expressMapper.selectByPrimaryKey(expressId);
                vo.getCommon().setShippingExpressName(express.geteName());
            }
        }

        return vo;
    }

    @Override
    public List<OrderLog> getOrderLogByOrderId(Integer id) {
        return orderLogMapper.selectByOrderId(id);
    }

    @Override
    public void evaluationAdd(Integer[] gevalOrderid,
                              Integer[] gevalOrdergoodsid, Integer[] gevalScores,
                              Integer[] gevalIsanonymous, String[] gevalContent, Member m) {
        int orderId = gevalOrderid[0];
        OrderVo vo = getOrderDetailById(orderId, m.getMemberId());
        if (vo == null || vo.getGoods() == null || vo.getGoods().size() != gevalOrderid.length) {
            return;
        }
        for (int index = 0; index < gevalOrderid.length; index++) {
            OrderGoods good = vo.getGoods().get(index);
            EvaluateGoods eva = new EvaluateGoods();
            eva.setGevalOrderid(gevalOrderid[index]);
            eva.setGevalOrderno(vo.getOrderSn());
            eva.setGevalOrdergoodsid(good.getGoodsId());
            eva.setGevalGoodsid(good.getGoodsId());
            eva.setGevalGoodsname(good.getGoodsName());
            eva.setGevalGoodsprice(good.getGoodsPrice());
            eva.setGevalGoodsimage(good.getGoodsImage());
            eva.setGevalScores(gevalScores[index]);
            eva.setGevalContent(gevalContent[index]);
            eva.setGevalIsanonymous(gevalIsanonymous[index] == 1);
            eva.setGevalStoreid(good.getStoreId());
            eva.setGevalStorename(vo.getStoreName());
            eva.setGevalFrommemberid(m.getMemberId());
            eva.setGevalFrommembername(m.getMemberName());
            eva.setGevalState(false);
            evaluateGoodsMapper.insert(eva);
        }
        Order o = new Order();
        o.setEvaluationState("1");
        o.setOrderId(orderId);
        orderMapper.updateByPrimaryKeySelective(o);

        //记录订单评价时间
        OrderCommon orderCommon = orderCommonMapper.selectByPrimaryKey(orderId);
        orderCommon.setEvaluationTime(DateUtil.unixTimeStampInt().intValue());
        orderCommonMapper.updateByPrimaryKeySelective(orderCommon);
    }

    @Override
    public void evaluationList(EvaluateGoodsSearchBean page) {
        page.setResultList(evaluateGoodsMapper.selectByMember(page));
    }

    @Override
    public EvaluateGoods getEvaluateById(Integer id, Integer memberId) {
        EvaluateGoods goods = evaluateGoodsMapper.selectByPrimaryKey(id);
        if (goods.getGevalFrommemberid().intValue() == memberId.intValue()) {
            return goods;
        }
        return null;
    }

    @Override
    public void updateEvaluateById(EvaluateGoodsVo vo) {
        evaluateGoodsMapper.updateByPrimaryMemberSelective(vo);
    }

    //	private WxJSSdkService wxJSSdkService;
    @Override
    @Transactional
    public PdLog cancelOrder(OrderVo vo) {
        Map<String, Integer> param = new HashMap<String, Integer>();
        param.put("id", vo.getOrderId());
        param.put("buyerId", vo.getBuyerId());
        OrderVo getOrder = orderMapper.selectById(param);
        PdLog pdLog = new PdLog();
        if (getOrder != null && getOrder.getOrderState().equals("20")) {
            vo.setFinnshedTime(DateUtil.toUnixTimeStamp(DateUtil.toTimeString(new Date())));
            vo.setOrderState(OrderStatusEnum.CANCEL.getValue() + "");
            orderMapper.updateByPrimaryKeySelective(vo);
            String pay_type = getOrder.getPaymentCode();
            if (pay_type.equals("1")) {
                Member mb = memberMapper.getMemberById(getOrder.getBuyerId());
                mb.setFreezePredeposit(mb.getFreezePredeposit().subtract(getOrder.getPdAmount()));
                mb.setAvailablePredeposit(mb.getAvailablePredeposit().add(getOrder.getPdAmount()));
                memberMapper.updateMemberBaseInfo(mb);

                RefundReturn refundReturn = new RefundReturn();
                refundReturn.init();
                refundReturn.setAddTime(DateUtil.unixTimeStampInt().intValue());
                refundReturn.setStoreName(getOrder.getStoreName());
                refundReturn.setStoreId(getOrder.getStoreId());
                refundReturn.setBuyerId(getOrder.getBuyerId());
                refundReturn.setBuyerName(getOrder.getBuyerName());
                refundReturn.setGoodsId(0);
                refundReturn.setOrderGoodsId(0);
                refundReturn.setReasonId(0);
                refundReturn.setReasonInfo("全额退款");
                refundReturn.setRefundAmount(getOrder.getOrderAmount());
                refundReturn.setRefundState(3);
                refundReturn.setOrderId(getOrder.getOrderId());
                refundReturn.setOrderSn(getOrder.getOrderId() + "");
                refundReturn.setRefundSn(getOrder.getPaySn());
                refundReturn.setRefundType(1);
                refundReturn.setSellerState(1);
                refundReturn.setReturnChannel(getOrder.getPaymentCode());
                refundReturn.setOrderAmount(getOrder.getOrderAmount());
                refundReturnMapper.insertSelective(refundReturn);
//				wxRefund.

            } else if (pay_type.equals("2")) {
                Member mb = memberMapper.getMemberById(getOrder.getBuyerId());
                mb.setAvailablePredeposit(mb.getAvailablePredeposit().add(getOrder.getOrderAmount()));
                memberMapper.updateMemberBaseInfo(mb);
                pdLog.setLgMemberId(mb.getMemberId());
                pdLog.setLgMemberName(mb.getMemberName());
                pdLog.setLgAvAmount(getOrder.getOrderAmount());
                pdLog.setLgAddTime(Integer.parseInt(DateUtil.unixTimeStamp()));
                pdLog.setLgDesc(PdLogTypeEnum.ORDER_CANCEL.getText() + getOrder.getOrderSn());
                pdLog.setLgType("order_cancel");
                pdLogMapper.insertSelective(pdLog);
            }
            //获取订单商品列表 依次还原商品库存以及销量
            List<OrderGoods> goodsList = orderGoodsMapper.findOrderGoodsListByOrderId(getOrder.getOrderId());
            for (OrderGoods goods : goodsList) {
                goodsMapper.updateGoodsStorageDirect(goods);
            }
        }
        return pdLog;
    }

    @Override
    public void takeOrder(Integer orderId, Integer memberId) {
        Map<String, Integer> param = new HashMap<String, Integer>();
        param.put("id", orderId);
        param.put("buyerId", memberId);
        OrderVo getOrder = orderMapper.selectById(param);
        if (getOrder != null) {
            getOrder.setOrderState(OrderStatusEnum.COMPLETE.getValue() + "");
            getOrder.setLockState(0);
            orderMapper.updateByPrimaryKeySelective(getOrder);
        }
    }

    @Override
    public RefundReturn retrunOrder(Integer orderId, String buyerMessage,
                                    String[] gevalImage, Integer memberId) {
        Map<String, Integer> param = new HashMap<String, Integer>();
        param.put("id", orderId);
        param.put("buyerId", memberId);
        OrderVo vo = orderMapper.selectById(param);
        RefundReturn r = new RefundReturn();
        if (vo != null && vo.getOrderState().equals(OrderStatusEnum.WAIT_SHIPMENTS.getValue() + "") && (vo.getLockState() == null || vo.getLockState() == 0)) {
            Order o = new Order();
            o.setOrderId(orderId);
            o.setLockState(1);
            o.setRefundState(2);
            orderMapper.updateByPrimaryKeySelective(o);

            r.init();
            r.setOrderId(orderId);
            r.setOrderSn(vo.getOrderSn() + "");
            r.setStoreId(vo.getStoreId());
            r.setStoreName(vo.getStoreName());
            r.setBuyerId(vo.getBuyerId());
            r.setBuyerName(vo.getBuyerName());
            r.setRefundAmount(vo.getOrderAmount().subtract(vo.getShippingFee()));
            r.setSellerState(SellerStateEnum.PROCESSED.getValue());
            r.setBuyerMessage(buyerMessage);
            r.setReasonId(0);
            r.setReasonInfo("取消订单，全部退款");
            String picInfo = null;
            if (gevalImage != null) {
                for (String pic : gevalImage) {
                    if (pic != null && !pic.trim().equals("")) {
                        if (picInfo == null) {
                            picInfo = "";
                        } else if (picInfo.length() > 0) {
                            picInfo += ",";
                        }
                        picInfo += pic;
                    }
                }
            }
            r.setPicInfo(picInfo);
            r.setReturnChannel(vo.getPaymentCode());
            r.setOrderAmount(vo.getOrderAmount());
            refundReturnMapper.insertSelective(r);
        }
        return r;
    }
}
